package com.imonsoft.sqm.validator.basedata;

import com.imonsoft.sqm.pojo.basedata.IpicTarget;
import com.imonsoft.sqm.service.MessageUtil;
import com.imonsoft.sqm.service.basedata.IpicTargetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.*;

import java.util.ArrayList;
import java.util.List;

@Component("ipicTargetValidator")
public class IpicTargetValidator implements Validator {

	@Autowired
	private IpicTargetService ipicTargetService;

	@Override
	public boolean supports(Class<?> clazz) {
		return IpicTarget.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
	//	ValidationUtils.rejectIfEmptyOrWhitespace(errors, "supplierCode", "message.unique.ipictarget.year", "supplierCode required!");

	}

	public void methodAddValidate(Object target, Errors errors) {
		validate(target, errors);
		IpicTarget ipicTarget = (IpicTarget) target;
		List<IpicTarget> list = ipicTargetService.findList(ipicTarget);
		if (list.size() > 0) {
			errors.rejectValue("supplierCode", "message.unique.ipictarget.year", new Object[] {ipicTarget.getSupplierCode(),ipicTarget.getYear() }, "保存的供应商和年份不能有相同记录！");
		}
	}

	public void methodModifyValidate(Object target, Errors errors) {
		validate(target, errors);
		IpicTarget ipicTarget = (IpicTarget) target;
		List<IpicTarget> list = ipicTargetService.findList(ipicTarget);
		if (list.size() > 0) {
			errors.rejectValue("supplierCode", "message.unique.ipictarget.year", new Object[] { ipicTarget.getSupplierCode(), ipicTarget.getYear() }, "保存的供应商和年份不能有相同记录！");
		}
	}

	@Autowired
	private MessageUtil messageUtil;

	public List<String> getErrors(BindingResult result) {
		List<String> errors = new ArrayList<String>();
		for (ObjectError error : result.getAllErrors()) {
			errors.add(messageUtil.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage()));
		}
		return errors;
	}
}
